import { ILoginQuery, ILoginRes, IPaging, IUser, IUserListPayload } from '@/types';
import { storageUserInfo } from '@/utils';
import { requestClient } from './client';
// @ts-ignore
import md5 from 'md5';

/**
 * 用户登录
 * @param query 账号信息
 * @returns loginToken
 */
export async function login(query: ILoginQuery): Promise<ILoginRes> {
    const res: { data: ILoginRes } = await requestClient.post('/user/login', {
        mobile: query.account,
        passWord: md5(query.passWord),
    });
    storageUserInfo(res.data);
    return res.data;
}

/**
 * 用户列表
 * @param payload 
 */
export async function userList(query: IUserListPayload = { pageNo: 1, pageSize: 10, mobile: '' }): Promise<IPaging<IUser>> {
    return requestClient.get('/user/list', {
        params: query
    });
}

/**
 * 获取用户详情
 * @param id 用户id
 * @returns 
 */
export async function userDetail(id: string | number) {
    return requestClient.get('/user/' + id);
}

/**
 * 删除用户
 * @param id 用户id
 * @returns 
 */
export async function delUser(id: number) {
    return requestClient.delete('/user/' + id);
}

/**
 * 更新用户
 * @param data 用户信息
 * @returns 
 */
export async function updateUser(data: IUser) {
    const payload: Record<string, any> = {...data};
    if (payload.password) {
        payload.password = md5(payload.password);
    }
    return requestClient.patch('/user/update', payload);
}

/**
 * 新增用户
 * @param data 用户信息
 * @returns 
 */
export async function addUser(data: IUser & { password: string; }) {
    return requestClient.post('/user/add', {
        ...data,
        password: md5(data.password)
    });
}